package top.broncho.lottery.ui.ocr

import android.app.Application
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.launch
import top.broncho.lottery.data.IRepositoryManager
import top.broncho.lottery.data.obtainRoomDatabase
import top.broncho.lottery.db.AppDataBase
import top.broncho.lottery.db.LotteryEntity
import top.broncho.lottery.model.ocr.OcrResult
import top.broncho.lottery.ui.base.BaseViewModule
import top.broncho.lottery.ui.main.Result
import top.broncho.lottery.util.initAccessTokenLicenseFile
import top.broncho.lottery.util.parseResult
import top.broncho.lottery.util.recognizeAccurateBasic
import javax.inject.Inject

class OcrViewModule @Inject constructor(
    private val manager: IRepositoryManager,
    app: Application
) : BaseViewModule(app) {
    private var hasGotOrcToken = false
    val ocrResult = MutableLiveData<Result<OcrResult>>()
    val saveDataBaseState = MutableLiveData<Result<Boolean>>()

    suspend fun recognizeAccurate(path: String) {
        if (!hasGotOrcToken) {
            hasGotOrcToken = app.initAccessTokenLicenseFile()
        }
        if (!hasGotOrcToken) {
            ocrResult.postValue(Result(throwable = Exception("OCR初始化")))
            return
        }
        val generalResult = app.recognizeAccurateBasic(path)
        if (generalResult.jsonRes.isNullOrEmpty()) {
            ocrResult.postValue(Result(throwable = Exception("OCR转文字失败")))
            return
        }
        val lottery = generalResult.parseResult(
            path,
            (app.externalCacheDir.takeIf { it != null } ?: app.cacheDir).absolutePath)
        if (lottery.list.isNullOrEmpty()) {
            ocrResult.postValue(Result(throwable = Exception("解析彩票失败")))
            return
        }
        ocrResult.postValue(Result(lottery))
    }

    private suspend fun save2Db(ocrResult: OcrResult): Long {
        val entity = LotteryEntity(
            System.currentTimeMillis(),
            ocrResult.path,
            ocrResult.lotteryNo,
            ocrResult.lotteryDate,
            ocrResult.sellDate,
            ocrResult.cost,
            ocrResult.list
        )
        return manager.obtainRoomDatabase<AppDataBase>().lotteryDao().insert(entity)
    }

    fun onSave(ocrResult: OcrResult) = launch {
        val result = save2Db(ocrResult)
        saveDataBaseState.postValue(Result(result > 0))
    }
}